import { FC, memo, useEffect, useRef } from 'react'
import { Modal, Image, Button } from 'antd'
import styles from './index.less'
const FileViewer = require('react-file-viewer')
interface IProps {
  visible: boolean
  fileType: string
  filePath: string
  hide: () => any
}
const FilePreview: FC<IProps> = ({ visible, fileType, filePath, hide }) => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const audioRef = useRef<HTMLAudioElement>(null)
  const handleOk = () => {
    hide()
  }
  const handleCancel = () => {
    hide()
  }
  useEffect(() => {
    if (!visible) {
      // 弹窗关闭，视频暂停，播放时间清0
      videoRef.current?.pause()
      if (videoRef.current) {
        videoRef.current.currentTime = 0
      }

      // 清空音频
      audioRef.current?.pause()
      if (audioRef.current) {
        audioRef.current.currentTime = 0
      }
    }
  }, [visible])
  return (
    <>
      <Modal
        title="文件预览"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={window.innerWidth * 0.75}
        okText="确认"
        cancelText="取消"
        bodyStyle={{
          height: `${window.innerHeight * 0.7}px`,
          overflowY: 'auto'
        }}
        footer={[
          // 重点：定义右下角
          <Button onClick={handleOk}>关闭</Button>
        ]}
      >
        <div className={styles['modal-content']}>
          {['jpg', 'png', 'jpeg', 'gif', 'webp'].includes(fileType) ? (
            <Image src={`${filePath}`} />
          ) : ['mp4', 'webm', 'ogg'].includes(fileType) ? (
            <video
              src={`${filePath}`}
              controls
              width="100%"
              height="100%"
              ref={videoRef}
            >
              您的浏览器不支持 video 标签。
            </video>
          ) : ['pdf'].includes(fileType) ? (
            <iframe src={filePath} width="100%" height="100%"></iframe>
          ) : ['mp3', 'wav'].includes(fileType) ? (
            <audio src={filePath} controls muted loop ref={audioRef}></audio>
          ) : (
            <FileViewer fileType={fileType} filePath={filePath}></FileViewer>
          )}
        </div>
      </Modal>
    </>
  )
}

export default memo(FilePreview)
